#include <QtOpenGL>
#include "sphere.h"
#include <GL/glu.h>
#include <GL/glut.h>

Sphere::Sphere(const QVector3D& center, QObject *parent):Object3D(center, parent), radius(1.0)
{
}

void Sphere::drawGeometry(void)
{
    glBindTexture(GL_TEXTURE_2D, texture());

    GLUquadric *quad = gluNewQuadric();
    if (getSelected()) {
        gluQuadricDrawStyle(quad, GLU_LINE);
    } else {
        gluQuadricDrawStyle(quad, GLU_FILL);
    }
    gluQuadricNormals(quad, GLU_SMOOTH);
    gluQuadricTexture(quad, true);

    gluSphere(quad, radius, 30, 30);

    glBindTexture(GL_TEXTURE_2D, NULL);
}

float Sphere::intersectionWithLine(QVector3D direction, QVector3D eye)
{
    QVector3D worldCenter = center() + translation();

    float scaledRadius = radius*((float) getScaleFactor()/50);
    float a = QVector3D::dotProduct(direction, direction);
    float b = QVector3D::dotProduct(direction, eye - worldCenter);
    float c = QVector3D::dotProduct(eye - worldCenter, eye - worldCenter) - scaledRadius*scaledRadius;
    float delta = b*b - a*c;

    if (delta < 0.0) return NULL;

    return (-b - sqrt(delta)) / a;
}
